package org.sction.util;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

public class XMLUtils {
	private static final Logger logger = Logger.getLogger(XMLUtils.class);

	@SuppressWarnings("unchecked")
	public static <T> T readXML(Class<T> clazz, String xmlpath)
			throws Exception {
		try {
			Reader reader = new FileReader(xmlpath);
			JAXBContext context = JAXBContext.newInstance(clazz);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			return (T) unmarshaller.unmarshal(reader);
		} catch (Exception e) {
			logger.error(xmlpath + "不存在或格式错误！" + e.getMessage());
			throw e;
		}
	}

	public static void writeXML(Class<?> clazz, Object obj, String xmlpath)
			throws Exception {
		try {
			JAXBContext context = JAXBContext.newInstance(clazz);
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
			FileWriter fw = new FileWriter(xmlpath);
			marshaller.marshal(obj, fw);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			logger.error(xmlpath + "不存在或拒绝访问！" + e.getMessage());
			throw e;
		}
	}
}
